package com.rayo.accesscontrollercopy.module.main;

import android.animation.ObjectAnimator;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.github.johnkil.print.PrintView;
import com.github.ybq.android.spinkit.SpinKitView;
import com.github.ybq.android.spinkit.style.Wave;
import com.litesuits.common.utils.HexUtil;
import com.rayo.accesscontrollercopy.R;
import com.rayo.accesscontrollercopy.app.BaseFragment;
import com.rayo.accesscontrollercopy.config.Constants;
import com.rayo.accesscontrollercopy.config.GlobalVariables;
import com.rayo.accesscontrollercopy.config.Version;
import com.rayo.accesscontrollercopy.model.db.bean.EventData;
import com.rayo.accesscontrollercopy.model.db.bean.KeyData;
import com.rayo.accesscontrollercopy.model.db.bean.KeyUserData;
import com.rayo.accesscontrollercopy.model.db.bean.LockData;
import com.rayo.accesscontrollercopy.model.db.bean.LogData;
import com.rayo.accesscontrollercopy.model.db.bean.SiteData;
import com.rayo.accesscontrollercopy.model.db.dao.CurrentUserDao;
import com.rayo.accesscontrollercopy.model.db.dao.CurrentUserImpl;
import com.rayo.accesscontrollercopy.model.db.dao.EventDao;
import com.rayo.accesscontrollercopy.model.db.dao.EventImpl;
import com.rayo.accesscontrollercopy.model.db.dao.KeyDataDao;
import com.rayo.accesscontrollercopy.model.db.dao.KeyDataImp;
import com.rayo.accesscontrollercopy.model.db.dao.KeyUserDao;
import com.rayo.accesscontrollercopy.model.db.dao.KeyUserImpl;
import com.rayo.accesscontrollercopy.model.db.dao.LockDao;
import com.rayo.accesscontrollercopy.model.db.dao.LockImp;
import com.rayo.accesscontrollercopy.model.db.dao.SiteDao;
import com.rayo.accesscontrollercopy.model.db.dao.SiteImpl;
import com.rayo.accesscontrollercopy.module.adapter.LogAdapter;
import com.rayo.accesscontrollercopy.module.setting.SetKeyActivity;
import com.rayo.accesscontrollercopy.utils.AppUtils;
import com.rayo.accesscontrollercopy.utils.BroadcastUtils;
import com.rayo.accesscontrollercopy.utils.CancelUtils;
import com.rayo.accesscontrollercopy.utils.KeyTypeUtils;
import com.rayo.accesscontrollercopy.utils.TimeFormatUtil;
import com.rayo.accesscontrollercopy.utils.ToastUtils;
import com.rayo.keyholder.data.KeyHolderCmd;
import com.rayo.keyholder.data.KeyHolderData;
import com.rayo.keyholder.serialport.KeyHolderService;
import com.rayo.wallreader.data.KeyBasicInfo;
import com.rayo.wallreader.data.KeyEventInfo;
import com.rayo.wallreader.data.KeyType;
import com.rayo.wallreader.data.UserKeyInfo;
import com.rayo.wallreader.jni.WallreaderJni;
import com.rayo.wallreader.serialport.OnPortListener;
import com.rayo.wallreader.serialport.PortClass;
import com.rayo.wallreader.serialport.ReaderPort;
import com.rayo.wallreader.serialport.ReaderPortThread;
import com.rayo.wallreader.utils.TimeUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.OnClick;
import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.rayo.accesscontrollercopy.config.Constants.BACKLOCK;
import static com.rayo.accesscontrollercopy.config.Constants.BACKLOCKTIME;
import static com.rayo.accesscontrollercopy.config.Constants.CHECKCONTROLLER;
import static com.rayo.accesscontrollercopy.config.Constants.CHECKDOOR;
import static com.rayo.accesscontrollercopy.config.Constants.CLOSE;
import static com.rayo.accesscontrollercopy.config.Constants.CLOSECONTROLLER;
import static com.rayo.accesscontrollercopy.config.Constants.OPENCONTROLLER;
import static com.rayo.accesscontrollercopy.config.Constants.OPENDOOR;
import static com.rayo.accesscontrollercopy.module.main.MainActivity.DOOR_STATUS;
import static com.rayo.accesscontrollercopy.module.main.MainActivity.START;
import static com.rayo.accesscontrollercopy.module.main.MainActivity.STOP;
import static com.rayo.accesscontrollercopy.module.main.MainActivity.mKeyHolderService;


/**
 * Created by lyc-pc on 17/4/20.
 */

public class CollectFragment extends BaseFragment {


//    private SpinKitView mSvActivityCollectkeyLoading;
    private TextView mSvActivityCollectkeyLoading;

    private RecyclerView mRlvActivityCollectkey;

    private TextView mTvActivityCollectkeyKeytype;

    private TextView mTvActivityCollectkeyKeyid;

    private TextView mTvActivityCollectkeyIssuetime;

    private TextView mTvActivityCollectkeyStarttime;

    private TextView mTvActivityCollectkeyEndtime;
    private TextView mTvActivityCollectkeyPower;

    private Button mTvActivityCollectkeyWrite;

    private PrintView mPvActivityCollectkeyTime;

//    private ReaderService mReaderService;

    private Thread mThread;
    private ReaderPortThread mReaderPortThread;
    private boolean mResult = false;
    private KeyBasicInfo mKeyBasicInfo;
    private List<LogData> mList;
    private LogAdapter mLogAdapter;
    private int keyType;
    private String userid;
    private String issueTime;
    private String startTime;
    private String endTime;
    private String userName;
    private int errorCount = 0;
    private ObjectAnimator objectAnimator;
    private Subscription mSubscription;
    private int finishCount = 0;
    private String tagId = "";
    private String SN = "";
    private KeyUserDao mKeyUserDao = new KeyUserImpl();
    private KeyDataDao mKeyDataDao = new KeyDataImp();
    private CurrentUserDao mCurrentUserDao = new CurrentUserImpl();
    private boolean exit = false;
    private byte address;
    private String connect;
    private KeyData mKeyData;
    private int Action;
    private KeyDataDao keyDataDao = new KeyDataImp();

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 10:
                    Toast.makeText(getActivity(), R.string.noper, Toast.LENGTH_SHORT).show();
                    break;
//                case 1:
//                    BroadcastUtils.send(getActivity(), START);
//                    break;
                case 2:
                    Toast.makeText(getActivity(), R.string.connectkeyfail, Toast.LENGTH_SHORT).show();
                    break;
                case Constants.BACKLOCK:
                    Action = Constants.BACKLOCK;
                    byte[] keyBack = {0, 0, 0, 0};
                    mKeyHolderService.sendData(new KeyHolderData((byte) mKeyData.getType(), (byte) mKeyData.getAddress(), (byte) 0x02, keyBack));
                    break;
                case 0:
                    byte[] key = {};
                    mKeyHolderService.sendData(new KeyHolderData((byte) mKeyData.getType(), (byte) mKeyData.getAddress(), (byte) 0x01, key));
                    handler.sendEmptyMessageDelayed(0, 100);
                    break;
                case 1:
                    byte[] key1 = {};
                    mKeyHolderService.sendData(new KeyHolderData((byte) 1, (byte) mKeyData.getKeybox(), (byte) 0x01, key1));
                    handler.sendEmptyMessageDelayed(1, 100);
                    break;
                case 3:
//                    getView().getKeySussess();
                    break;
                case 4:
//                    getView().returnKeySuccess();
                    break;
                case 5:
                    Action = OPENCONTROLLER;
                    byte[] key2 = {1, 0, 0, 1};
                    mKeyHolderService.sendData(new KeyHolderData((byte)mKeyData.getType(),(byte)mKeyData.getAddress(),(byte) 0x02,key2));
                    break;
            }
        }
    };

    private BroadcastReceiver mKeyHolderReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            StringBuilder sb = new StringBuilder(64);
            final String action = intent.getAction();
            if (intent.getSerializableExtra(KeyHolderService.EXTRA_DATA) instanceof Integer) {
                return;
            }
            final KeyHolderData keyHolderData = (KeyHolderData) intent.getSerializableExtra(KeyHolderService.EXTRA_DATA);
            switch (action) {
                case KeyHolderService.ACTION_DATA_WRITE:
                    sb.append("CollectSend:");
                    sb.append(HexUtil.encodeHexStr(keyHolderData.getData()));
                    Log.e(getActivity().getClass().getSimpleName() + "write", sb.toString());
                    break;
                case KeyHolderService.ACTION_DATA_READ:
                    sb.append("CollectRead:");
                    sb.append(String.format("%02X", keyHolderData.getCmd()) + "-");
                    sb.append(HexUtil.encodeHexStr(keyHolderData.getData()));
                    if (keyHolderData.getCmd() == 2) {
                        if (com.rayo.wallreader.utils.HexUtil.encodeHexStr(keyHolderData.getData()).equals("01")) {
                            switch (Action) {
                                case BACKLOCK:
//                                    getView().finishActivity();
                                    break;
                                case CHECKDOOR:

                                    break;
                                case OPENDOOR:
                                    ToastUtils.showShortToast(getActivity(),"门已开启，请还入钥匙");
                                    handler.sendEmptyMessageDelayed(5,500);

                                    break;
                                case OPENCONTROLLER:
                                    handler.sendEmptyMessageDelayed(BACKLOCK,BACKLOCKTIME);
                                    Action = CHECKCONTROLLER;
                                    handler.sendEmptyMessage(0);
                                    break;
                                case CLOSECONTROLLER:
                                    Action = CHECKDOOR;
                                    handler.removeMessages(BACKLOCK);
                                    handler.sendEmptyMessage(1);
//                                    getModule().upDataControllerBean(mKeyData);
//                                    getContext().sendBroadcast(new Intent().setAction(MainActivity.ACTION));
                                    break;
                                case CLOSE:
//                                    getView().close();
                                    break;


                            }
                        }else {

                        }
                    } else if (keyHolderData.getCmd() == 1) {

                        if ((com.rayo.wallreader.utils.HexUtil.encodeHexStr(keyHolderData.getData()).startsWith("01", 0))) {

                            switch (Action) {
                                case CHECKDOOR:
                                    if (com.rayo.wallreader.utils.HexUtil.encodeHexStr(keyHolderData.getData()).substring(22, 24).equals("01")) {//01开
//                                        Action = OPENCONTROLLER;
//                                        byte[] key = {1, 0, 0, 1};
//                                        mKeyHolderService.sendData(new KeyHolderData((byte) mKeyData.getType(), (byte) mKeyData.getAddress(), (byte) 0x02, key));
                                    } else {
                                        handler.removeMessages(1);
                                        ToastUtils.showShortToast(getActivity(),"还入成功");
                                        getActivity().onBackPressed();
//                                        Action = OPENDOOR;
//                                        byte[] key = {1, 0, 0, 0};
//                                        mKeyHolderService.sendData(new KeyHolderData((byte) DOORTYPE, (byte) mKeyData.getBoxid(), (byte) 0x02, key));
                                    }
                                    break;
                                case CHECKCONTROLLER:
                                    if (!HexUtil.encodeHexStr(keyHolderData.getData()).substring(14, 22).equals("00000000")&&
                                            com.rayo.wallreader.utils.HexUtil.encodeHexStr(keyHolderData.getData()).substring(22, 24).equals("01" )) {
                                        ToastUtils.showShortToast(getActivity(),"钥匙已还入，请关闭柜门");
                                        mKeyData.setUse(false);
                                        keyDataDao.updateKeyData(mKeyData);
                                        Action = CLOSECONTROLLER;
                                        handler.removeMessages(0);
                                        byte[] key = {0, 0, 0, 0};
                                        mKeyHolderService.sendData(new KeyHolderData((byte) mKeyData.getType(), (byte) mKeyData.getAddress(), (byte) 0x02, key));
                                    }
                                    break;
                            }

                            if (!com.rayo.wallreader.utils.HexUtil.encodeHexStr(keyHolderData.getData()).substring(14, 22).equals("00000000")) {

                            }
                        }
                    }
//                    Log.e(getActivity().getClass().getSimpleName() + "read", sb.toString());
                    break;
                case KeyHolderService.ACTION_CLOSE:
                    break;
                case MainActivity.STATUS:
                    getActivity().onBackPressed();
                    break;
                default:
                    break;
            }
        }
    };

    private IntentFilter makeUpdateIntentFilter() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(KeyHolderService.ACTION_DATA_READ);
        intentFilter.addAction(KeyHolderService.ACTION_DATA_WRITE);
        intentFilter.addAction(KeyHolderService.ACTION_CLOSE);
        intentFilter.addAction(MainActivity.STATUS);
        return intentFilter;
    }


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_collectkey;
    }

    @Override
    protected void setupViews() {
        mSvActivityCollectkeyLoading = (TextView) rootView.findViewById(R.id.sv_activity_collectkey_loading);
        mRlvActivityCollectkey = (RecyclerView) rootView.findViewById(R.id.rlv_activity_collectkey);
        mTvActivityCollectkeyKeytype = (TextView) rootView.findViewById(R.id.tv_activity_collectkey_keytype);
        mTvActivityCollectkeyKeyid = (TextView) rootView.findViewById(R.id.tv_activity_collectkey_keyid);
        mTvActivityCollectkeyIssuetime = (TextView) rootView.findViewById(R.id.tv_activity_collectkey_issuetime);
        mTvActivityCollectkeyStarttime = (TextView) rootView.findViewById(R.id.tv_activity_collectkey_starttime);
        mTvActivityCollectkeyEndtime = (TextView) rootView.findViewById(R.id.tv_activity_collectkey_endtime);
        mTvActivityCollectkeyPower = (TextView) rootView.findViewById(R.id.tv_activity_collectkey_power);
        mTvActivityCollectkeyWrite = (Button) rootView.findViewById(R.id.tv_activity_collectkey_write);
        mPvActivityCollectkeyTime = (PrintView) rootView.findViewById(R.id.pv_activity_collectkey_time);

    }

    @Override
    protected void initialized() {

        MainActivity.collect = true;
        finishCount = 0;
        getActivity().registerReceiver(mKeyHolderReceiver, makeUpdateIntentFilter());
        mList = new ArrayList<>();
        mLogAdapter = new LogAdapter(getContext(), mList);
        mRlvActivityCollectkey.setLayoutManager(new LinearLayoutManager(getContext()));
        mRlvActivityCollectkey.setAdapter(mLogAdapter);
//        mSvActivityCollectkeyLoading.setIndeterminateDrawable(new Wave());
        mSvActivityCollectkeyLoading.setText(getString(R.string.return_hint));
        doListen();
        mTvActivityCollectkeyWrite.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        errorCount = 0;
        mTvActivityCollectkeyWrite.setVisibility(View.GONE);
        mSvActivityCollectkeyLoading.setVisibility(View.VISIBLE);
        doListen();
    }

    private void doListen() {
        List<PortClass> port = new ArrayList<>();
        PortClass portClass = new PortClass(ReaderPort.DETIVER_2,true,true,false);
        port.add(portClass);
        stop();
        mReaderPortThread = new ReaderPortThread(port) {

            @Override
            protected void onSendNfcKeyReader(String s, int i) {
                mKeyBasicInfo = new KeyBasicInfo();
                mKeyBasicInfo.setKeyType(KeyBasicInfo.NFC_KEY);
                byte[] code = new byte[16];
                byte[] sys_Code = HexUtil.decodeHex(GlobalVariables.getInstance().getmSiteData().getSyscode().toCharArray());
                if (null != sys_Code && 8 == sys_Code.length) {
                    int ret = WallreaderJni.getmInstance().des(1, sys_Code, sys_Code.length, code);
                    if (ret > 0) {

                        System.arraycopy(code, 0, mKeyBasicInfo.getSysCode(), 0, 4);
//                        System.arraycopy(code, 0, keyBasicInfo.getSysCode(), 0, 4);
//                        System.arraycopy(code, 0,  this.cardBasicInfo.getSysCode(), 0, 4);
                    }
                }
                byte[] reg_Code = HexUtil.decodeHex(GlobalVariables.getInstance().getmSiteData().getRegcode().toCharArray());
                if (null != reg_Code && 8 == reg_Code.length) {
                    int ret = WallreaderJni.getmInstance().des(1, reg_Code, reg_Code.length, code);
                    if (ret > 0) {
                        System.arraycopy(code, 0, mKeyBasicInfo.getRegCode(), 0, 4);
//                        System.arraycopy(code, 0, keyBasicInfo.getRegCode(), 0, 4);
//                        System.arraycopy(code, 0, this.cardBasicInfo.getRegCode(), 0, 4);
                    }
                }
                if (finishCount != 2) {
                    connect = "NFC";
                    connectNFCKey();
                }
                else if (finishCount==2){

                    byte reg[] = {49,49,49,49};
                    byte sys[] = {54,54,54,54};
                    mKeyBasicInfo.setRegCode(reg);
                    mKeyBasicInfo.setSysCode(sys);

                    mReaderPortThread.getmPortReadBiz().findKey(mKeyBasicInfo, new OnPortListener.OnFindListener() {
                        @Override
                        public void findSuccess() {



                            KeyBasicInfo keyBasicInfo = new KeyBasicInfo();
                            keyBasicInfo.setRegCode(HexUtil.decodeHex(AppUtils.getDecode(GlobalVariables.getInstance().getmSiteData().getRegcode()).toCharArray()));
                            keyBasicInfo.setSysCode(HexUtil.decodeHex(AppUtils.getDecode(GlobalVariables.getInstance().getmSiteData().getSyscode()).toCharArray()));

                            mReaderPortThread.getmPortReadBiz().registerKey(keyBasicInfo, new OnPortListener.OnWriteKeyListener() {
                                @Override
                                public void writeKeySuccess() {
                                    mResult=true;
                                    open();
                                }

                                @Override
                                public void writeKeyFailed() {
                                    Log.e("write", "Write key failed");
                                    mResult = false;
                                }
                            });
                        }

                        @Override
                        public void findFailed() {
                            mResult = false;
                            handler.sendEmptyMessage(2);
                        }
                    });

                    this.stop();
                }



                if (!mResult) {
                    if (exit) {
                        errorCount++;
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (errorCount == 3) {
                                    Toast.makeText(getContext(), R.string.read_key_failed, Toast.LENGTH_SHORT).show();
                                    mSvActivityCollectkeyLoading.setVisibility(View.GONE);
                                    mTvActivityCollectkeyWrite.setVisibility(View.VISIBLE);
                                } else if (errorCount < 3) {
                                    doListen();
                                }
                            }
                        });
                    } else {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getContext(), getString(R.string.This_key_is_not_registered), Toast.LENGTH_SHORT).show();
                                mSvActivityCollectkeyLoading.setVisibility(View.GONE);
                            }
                        });
                    }
                } else {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mLogAdapter.notifyDataSetChanged();
                            if (keyType == KeyType.USER_KEY.toInteger()) {
                                mTvActivityCollectkeyKeytype.setText(getString(R.string.key_type) + getString(R.string.user_key) + "");
                            } else {
                                mTvActivityCollectkeyKeytype.setText(getString(R.string.key_type) + getString(R.string.unknow_user) + "");
                            }
                            if (TextUtils.isEmpty(userName)) {
                                mTvActivityCollectkeyKeyid.setText(getString(R.string.user) + getString(R.string.unknow_user));
                            } else {
                                mTvActivityCollectkeyKeyid.setText(getString(R.string.user) + userName);
                            }
                            if (TextUtils.isEmpty(issueTime)) {
                                mTvActivityCollectkeyIssuetime.setText(getString(R.string.key_issue_time) + getString(R.string.unknow_user));
                            } else {
                                mTvActivityCollectkeyIssuetime.setText(getString(R.string.key_issue_time) + issueTime);
                            }
                            if (TextUtils.isEmpty(startTime)) {
                                mTvActivityCollectkeyStarttime.setText(getString(R.string.key_start_time) + getString(R.string.unknow_user));
                            } else {
                                mTvActivityCollectkeyStarttime.setText(getString(R.string.key_start_time) + startTime);
                            }
                            if (TextUtils.isEmpty(endTime)) {
                                mTvActivityCollectkeyEndtime.setText(getString(R.string.key_end_time) + getString(R.string.unknow_user));
                            } else {
                                mTvActivityCollectkeyEndtime.setText(getString(R.string.key_end_time) + endTime);
                            }
                            mTvActivityCollectkeyPower.setText(getString(R.string.key_lock_power)+mKeyBasicInfo.getPower());
                            Toast.makeText(getContext(), R.string.read_key_successful, Toast.LENGTH_SHORT).show();
                            mSvActivityCollectkeyLoading.setVisibility(View.GONE);
                        }
                    });
                }
            }

            @Override
            protected void onSendBleKeyReader(String s, int i) {

                SiteDao siteDao = new SiteImpl();
                SiteData siteData = siteDao.findFirst();
                if (siteData==null){
                    handler.sendEmptyMessage(10);
                    return;
                }
                if (!siteData.getSupportkey().contains("BLE")){
                    handler.sendEmptyMessage(10);
                    return;
                }

                mKeyBasicInfo = new KeyBasicInfo();
                mKeyBasicInfo.setKeyType(KeyBasicInfo.BLE_KEY);
                byte[] code = new byte[16];
                byte[] sys_Code = HexUtil.decodeHex(GlobalVariables.getInstance().getmSiteData().getSyscode().toCharArray());
                if (null != sys_Code && 8 == sys_Code.length) {
                    int ret = WallreaderJni.getmInstance().des(1, sys_Code, sys_Code.length, code);
                    if (ret > 0) {
                        System.arraycopy(code, 0, mKeyBasicInfo.getSysCode(), 0, 4);
//                        System.arraycopy(code, 0,  this.cardBasicInfo.getSysCode(), 0, 4);
                    }
                }
                byte[] reg_Code = HexUtil.decodeHex(GlobalVariables.getInstance().getmSiteData().getRegcode().toCharArray());
                if (null != reg_Code && 8 == reg_Code.length) {
                    int ret = WallreaderJni.getmInstance().des(1, reg_Code, reg_Code.length, code);
                    if (ret > 0) {
                        System.arraycopy(code, 0, mKeyBasicInfo.getRegCode(), 0, 4);
//                        System.arraycopy(code, 0, this.cardBasicInfo.getRegCode(), 0, 4);
                    }
                }
                if (finishCount != 2) {
                    connect = "BLE";
                    connectBLEKey();
                }
                else if (finishCount==2){


                    mReaderPortThread.getmPortReadBiz().findKey(mKeyBasicInfo, new OnPortListener.OnFindListener() {
                        @Override
                        public void findSuccess() {

                            mKeyBasicInfo.setRegCode(HexUtil.decodeHex(AppUtils.getDecode(GlobalVariables.getInstance().getmSiteData().getRegcode()).toCharArray()));
                            mKeyBasicInfo.setSysCode(HexUtil.decodeHex(AppUtils.getDecode(GlobalVariables.getInstance().getmSiteData().getSyscode()).toCharArray()));

                            mReaderPortThread.getmPortReadBiz().registerKey(mKeyBasicInfo, new OnPortListener.OnWriteKeyListener() {
                                @Override
                                public void writeKeySuccess() {
                                    mResult=true;
                                    open();
                                }

                                @Override
                                public void writeKeyFailed() {
                                    Log.e("write", "Write key failed");
                                    mResult = false;
                                }
                            });
                        }

                        @Override
                        public void findFailed() {

                            byte reg[] = {49,49,49,49};
                            byte sys[] = {54,54,54,54};
                            mKeyBasicInfo.setRegCode(reg);
                            mKeyBasicInfo.setSysCode(sys);
                            mReaderPortThread.getmPortReadBiz().findKey(mKeyBasicInfo, new OnPortListener.OnFindListener() {

                                @Override
                                public void findSuccess() {
                                    mKeyBasicInfo.setRegCode(HexUtil.decodeHex(AppUtils.getDecode(GlobalVariables.getInstance().getmSiteData().getRegcode()).toCharArray()));
                                    mKeyBasicInfo.setSysCode(HexUtil.decodeHex(AppUtils.getDecode(GlobalVariables.getInstance().getmSiteData().getSyscode()).toCharArray()));

                                    mReaderPortThread.getmPortReadBiz().registerKey(mKeyBasicInfo, new OnPortListener.OnWriteKeyListener() {
                                        @Override
                                        public void writeKeySuccess() {
                                            mResult=true;
                                            open();
                                        }

                                        @Override
                                        public void writeKeyFailed() {
                                            Log.e("write", "Write key failed");
                                            mResult = false;
                                        }
                                    });
                                }

                                @Override
                                public void findFailed() {
                                    mResult = false;
                                    handler.sendEmptyMessage(2);
                                }
                            });
                        }
                    });

                    this.stop();
                }
                if (!mResult) {
                    errorCount++;
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (errorCount == 3) {
                                Toast.makeText(getContext(), R.string.read_key_failed, Toast.LENGTH_SHORT).show();
                                mSvActivityCollectkeyLoading.setVisibility(View.GONE);
                                mTvActivityCollectkeyWrite.setVisibility(View.VISIBLE);
                            } else if (errorCount < 3) {
                                doListen();
                            }
                        }
                    });
                } else {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mLogAdapter.notifyDataSetChanged();
                            mTvActivityCollectkeyKeytype.setText(getString(R.string.key_type) + KeyTypeUtils.get(getContext(), keyType));
                            if (TextUtils.isEmpty(userName)) {
                                mTvActivityCollectkeyKeyid.setText(getString(R.string.user) + getString(R.string.unknow_user));
                            } else {
                                mTvActivityCollectkeyKeyid.setText(getString(R.string.user) + userName);
                            }
                            if (TextUtils.isEmpty(issueTime)) {
                                mTvActivityCollectkeyIssuetime.setText(getString(R.string.key_issue_time) + getString(R.string.unknow_user));
                            } else {
                                mTvActivityCollectkeyIssuetime.setText(getString(R.string.key_issue_time) + issueTime);
                            }
                            if (TextUtils.isEmpty(startTime)) {
                                mTvActivityCollectkeyStarttime.setText(getString(R.string.key_start_time) + getString(R.string.unknow_user));
                            } else {
                                mTvActivityCollectkeyStarttime.setText(getString(R.string.key_start_time) + startTime);
                            }
                            if (TextUtils.isEmpty(endTime)) {
                                mTvActivityCollectkeyEndtime.setText(getString(R.string.key_end_time) + getString(R.string.unknow_user));
                            } else {
                                mTvActivityCollectkeyEndtime.setText(getString(R.string.key_end_time) + endTime);
                            }
                            mTvActivityCollectkeyPower.setText(getString(R.string.key_lock_power)+mKeyBasicInfo.getPower()+"%");
                            Toast.makeText(getContext(), R.string.read_key_successful, Toast.LENGTH_SHORT).show();
                            mSvActivityCollectkeyLoading.setVisibility(View.GONE);
                        }
                    });
                }
            }
            @Override
            protected void onSendCardReader(String s, int i, byte[] bytes) {

            }

            @Override
            protected void onNoReader(String s, int i) {

            }

            @Override
            protected void onPlugInRelay(String s, int i) {

            }

            @Override
            protected void onStopReader() {

            }

        };
        mThread = new Thread(mReaderPortThread);
        mThread.start();
    }

    private void connectNFCKey(){
        if (connectKey(mReaderPortThread, mKeyBasicInfo)) {

            SiteDao siteDao = new SiteImpl();
            SiteData siteData = siteDao.findFirst();
            if (siteData.getSupportkey()==null){
                handler.sendEmptyMessage(10);
                mResult=false;


                this.stop();
                return;
            }
            if (mKeyBasicInfo.getVersion().contains("RCLB")){
                if (!siteData.getSupportkey().substring(0,3).equals("NFC")){
                    handler.sendEmptyMessage(10);
                    mResult=false;
                    this.stop();
                    return;
                }
            }else if (mKeyBasicInfo.getVersion().contains("B03014")){
                if (!siteData.getSupportkey().contains("MiniNFC")){
                    handler.sendEmptyMessage(10);
                    mResult=false;
                    this.stop();
                    return;
                }
            }
            KeyType key = KeyType.fromInt(mKeyBasicInfo
                    .getType());
            Log.e("sdsdsd", key + "" + "  " + finishCount + "");
            if (finishCount == 1) {
                resetKey(mReaderPortThread, mKeyBasicInfo);
            } else if (finishCount == 0) {
                readKey(mReaderPortThread, key);
                if (mResult) {
                    resetKey(mReaderPortThread, mKeyBasicInfo);
                }
            }
        }
    }
    private void connectBLEKey(){
        if (connectKey(mReaderPortThread, mKeyBasicInfo)) {
            KeyType key = KeyType.fromInt(mKeyBasicInfo
                    .getType());
            Log.e("sdsdsd", key + "" + "  " + finishCount + "");
            if (finishCount == 1) {
                resetKey(mReaderPortThread, mKeyBasicInfo);
            } else if (finishCount == 0) {
                readKey(mReaderPortThread, key);
                if (mResult) {
                    resetKey(mReaderPortThread, mKeyBasicInfo);
                }
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        MainActivity.collect = false;
        clearAni();
        mIHardware = null;
        stop();
        handler.removeCallbacksAndMessages(null);
        BroadcastUtils.send(getActivity(), START);
        getActivity().unregisterReceiver(mKeyHolderReceiver);
        CancelUtils.unsubscribe(mSubscription);
    }

    private void stop() {
        if (mReaderPortThread != null && !mReaderPortThread.isStop) {
            mReaderPortThread.stop();
        }
    }

    private boolean connectKey(ReaderPortThread mReaderPortThread, final KeyBasicInfo pKeyBasicInfo) {

        mReaderPortThread.getmPortReadBiz().findKey(pKeyBasicInfo, new OnPortListener.OnFindListener() {
            @Override
            public void findSuccess() {
                String txt = "Find key successfully \n";
                txt += "Key Id: " + pKeyBasicInfo.getKeyId() + "\n";
                txt += "Key Type: "
                        + String.format("%2X", pKeyBasicInfo.getType())
                        + "\n";
                txt += "Key Group Id: " + pKeyBasicInfo.getGroupId()
                        + "\n";
                txt += "Key Version: " + pKeyBasicInfo.getVersion()
                        + "\n";
                txt += "Key Serial Number: "
                        + HexUtil.encodeHexStr(pKeyBasicInfo
                        .getSerial()) + "\n";
                txt += "Key Time: "
                        + TimeFormatUtil.localDateTimeFormat(TimeUtils
                        .dateFromNotYMDWHMS(
                                HexUtil.encodeHexStr(pKeyBasicInfo
                                        .getKeyTime()))
                        .getTime()) + "\n";
                Log.e("txt", txt);
                keyType = pKeyBasicInfo.getType();
                userid = String.valueOf(pKeyBasicInfo.getKeyId());
                KeyUserData keyUserData = mKeyUserDao.findByUserid(userid);
                if (!keyUserData.equals("0")) {
                    if (GlobalVariables.getInstance().getmSystemData().getNameFormat() == 0) {
                        userName = keyUserData.getFname() + " " + keyUserData.getLname();
                    } else {
                        userName = keyUserData.getLname() + " " + keyUserData.getFname();
                    }

                } else {
                    userName = getString(R.string.unknow_user)+"("+userid+""+")";
                }

                SN = HexUtil.encodeHexStr(pKeyBasicInfo
                        .getSerial());
                issueTime = TimeFormatUtil.showDateTime(getContext(), TimeFormatUtil
                        .dateFromNotYMDHM("20"+HexUtil.encodeHexStr(pKeyBasicInfo.getKeyIssueTime())));
                startTime = TimeFormatUtil.showDateTime(getContext(), TimeFormatUtil
                        .dateFromNotYMDHM("20"+HexUtil.encodeHexStr(pKeyBasicInfo.getBeginTime())));
                endTime = TimeFormatUtil.showDateTime(getContext(), TimeFormatUtil
                        .dateFromNotYMDHM("20"+HexUtil.encodeHexStr(pKeyBasicInfo.getEndTime())));
                mResult = true;
                mKeyData = mKeyDataDao.getKeyDataBySerialnumber(HexUtil.encodeHexStr(pKeyBasicInfo
                        .getSerial()));

                if (mKeyData == null) {

                    exit=false;
                    mResult = false;
                } else {
                    exit=true;
                    mResult = true;
//                    List<KeyData> keyDataList = mKeyDataDao.getKeyDataByKeyBoxId(keyData.getKeybox());
//                    MainActivity.OldCount=0;
//                    for (int i=0;i<keyDataList.size();i++){
//                        if (!keyDataList.get(i).isUse()){
//                            MainActivity.OldCount++;
//                        }
//                    }
                }
            }

            @Override
            public void findFailed() {
                mResult = false;
                exit=true;
                byte reg[] = {49,49,49,49};
                byte sys[] = {54,54,54,54};
                mKeyBasicInfo.setRegCode(reg);
                mKeyBasicInfo.setSysCode(sys);
                if (connect.equals("NFC")){
                    connectNFCKey();
                }else if (connect.equals("BLE")){
                    connectBLEKey();
                }

                Log.e(getContext().getClass().getSimpleName() + "findkeyfailed", "findkeyfailed");
            }
        });

//        mReaderPortThread.getmPortReadBiz().findKey(pKeyBasicInfo,
//                new OnPortListener.OnFindKeyListener() {
//                    @Override
//                    public void findKeySuccess() {
//                        // TODO Auto-generated method stub
//                        String txt = "Find key successfully \n";
//                        txt += "Key Id: " + pKeyBasicInfo.getKeyId() + "\n";
//                        txt += "Key Type: "
//                                + String.format("%2X", pKeyBasicInfo.getType())
//                                + "\n";
//                        txt += "Key Group Id: " + pKeyBasicInfo.getGroupId()
//                                + "\n";
//                        txt += "Key Version: " + pKeyBasicInfo.getVersion()
//                                + "\n";
//                        txt += "Key Serial Number: "
//                                + HexUtil.encodeHexStr(pKeyBasicInfo
//                                .getSerial()) + "\n";
//                        txt += "Key Time: "
//                                + TimeUtils.localDateTimeFormat(TimeUtils
//                                .dateFromNotYMDWHMS(
//                                        HexUtil.encodeHexStr(pKeyBasicInfo
//                                                .getKeyTime()))
//                                .getTime()) + "\n";
//                        Log.e("txt", txt);
//                        keyType = pKeyBasicInfo.getType();
//                        userid =String.valueOf(pKeyBasicInfo.getKeyId());
//                        userName=getString(R.string.unknow_user);
//                        SN=HexUtil.encodeHexStr(pKeyBasicInfo
//                                .getSerial());
//                        mResult = true;
//                    }
//
//                    @Override
//                    public void findKeyFailed() {
//                        // TODO Auto-generated method stub
//                        mResult = false;
//                        Log.e(getContext().getClass().getSimpleName() + "findkeyfailed", "findkeyfailed");
//                    }
//                });
        return mResult;
    }

    private void readKey(ReaderPortThread mReaderPortThread, KeyType key) {
        if (null == key) {
            Log.e(getContext().getClass().getSimpleName() + "readkey", "UnKnow Key");
            return;
        }
        switch (key) {
            case USER_KEY:
                //
//                readUserKey(mReaderPortThread, mKeyDefineData.getmKeyBasicInfo(),
//                        mKeyDefineData.newUserKeyInfo());
                Log.e(getContext().getClass().getSimpleName() + "readkey", "User Key");
                readKeyEvent(mReaderPortThread, mKeyBasicInfo, new KeyEventInfo());
                break;
//            case SETTING_KEY:
//                setText("Setting Key");
//                readKeyEvent(mReaderPortThread, mKeyDefineData.getmKeyBasicInfo(),
//                        mKeyDefineData.newKeyEventInfo());
//                for (KeyEventInfo.Event e : mKeyDefineData.getmKeyEventInfo()
//                        .getEventList()) {
//                    setText(e.ToString());
//                }
//                break;
//            case SYSCODE_KEY:
//                setText("System-Code Key");
//                break;
//            case EVENT_KEY:
//                setText("Event Key");
//                readKeyEvent(mReaderPortThread, mKeyDefineData.getmKeyBasicInfo(),
//                        mKeyDefineData.newKeyEventInfo());
//                // for (KeyEventInfo.Event e : mKeyDefineData.getmKeyEventInfo()
//                // .getEventList()) {
//                // setText(e.ToString());
//                // }
//                break;
//            case LOSS_KEY:
//                setText("BlackList Key");
//                break;
//            case ENG_KEY:
//                readProKey(mReaderPortThread, mKeyDefineData.getmKeyBasicInfo(),
//                        mKeyDefineData.newProKey());
//                setText("Engineering Key");
//                setText("Issue Key DateTime: "
//                        + TimeUtils
//                        .localDateTimeFormat(TimeUtils
//                                .dateFromNotYMDHM(HexUtil
//                                        .encodeHexStr(mKeyDefineData
//                                                .getmProKeyInfo()
//                                                .getKeyIssueTime()))));
//                setText("Start DateTime: "
//                        + TimeUtils.localDateTimeFormat(TimeUtils
//                        .dateFromNotYMDHM(HexUtil
//                                .encodeHexStr(mKeyDefineData
//                                        .getmProKeyInfo()
//                                        .getEngineeringKeyStart()))));
//                setText("End DateTime: "
//                        + TimeUtils.localDateTimeFormat(TimeUtils
//                        .dateFromNotYMDHM(HexUtil
//                                .encodeHexStr(mKeyDefineData
//                                        .getmProKeyInfo()
//                                        .getEngineeringKeyEnd()))));
//                readKeyEvent(mReaderPortThread, mKeyDefineData.getmKeyBasicInfo(),
//                        mKeyDefineData.newKeyEventInfo());
//                // for (KeyEventInfo.Event e : mKeyDefineData.getmKeyEventInfo()
//                // .getEventList()) {
//                // setText(e.ToString());
//                // }
//                break;
//            case READLOCKID_KEY:
//                readProKey(mReaderPortThread, mKeyDefineData.getmKeyBasicInfo(),
//                        mKeyDefineData.newProKey());
//                setText("Read LockId Key");
//                setText("LockId: "
//                        + HexUtil.encodeHexStr(mKeyDefineData.getmProKeyInfo()
//                        .getReadLockIdKey()));
//                break;
//            case READLOCKNUM_KEY:
//                readProKey(mReaderPortThread, mKeyDefineData.getmKeyBasicInfo(),
//                        mKeyDefineData.newProKey());
//                setText("Read Lock Serial Number Key");
//                setText("Lock Serial Number: "
//                        + HexUtil.encodeHexStr(mKeyDefineData.getmProKeyInfo()
//                        .getReadLockSerialKey()));
//                break;
            case EMERGENCY_KEY:
                readKeyEvent(mReaderPortThread, mKeyBasicInfo, new KeyEventInfo());
                break;
//            case EMPTY_KEY:
//                setText("Empty Key");
//                break;
            default:
                break;
        }
    }

//    private void readUserKey(ReaderPortThread mReaderPortThread,
//                             final KeyBasicInfo pKeyBasicInfo, UserKeyInfo pUserKeyInfo) {
//        mReaderPortThread.getmPortReadBiz().readUserKey(pKeyBasicInfo,
//                pUserKeyInfo, new OnPortListener.OnReadUserKeyListener() {
//                    @Override
//                    public void readUserKeySuccess() {
//                        // TODO Auto-generated method stub
//                        Log.e(getContext().getClass().getSimpleName() + "userkey", "\nRead user key successfully \n");
//                        mResult = true;
////                        Log.e("userkey", "Issue Key DateTime: "
////                                + TimeUtils.localDateTimeFormat(TimeUtils
////                                .dateFromNotYMDHM(HexUtil
////                                        .encodeHexStr(mKeyDefineData
////                                                .getUserKeyInfo()
////                                                .getKeyIssueTime()))));
////                        Log.e("userkey", "Start DateTime: "
////                                + TimeUtils.localDateTimeFormat(TimeUtils
////                                .dateFromNotYMDHM(HexUtil
////                                        .encodeHexStr(mKeyDefineData
////                                                .getUserKeyInfo()
////                                                .getKeyStartTime()))));
////                        Log.e("userkey", "End DateTime: "
////                                + TimeUtils.localDateTimeFormat(TimeUtils
////                                .dateFromNotYMDHM(HexUtil
////                                        .encodeHexStr(mKeyDefineData
////                                                .getUserKeyInfo()
////                                                .getKeyEndTime()))));
//                        issueTime = TimeFormatUtil.showDateTime(getContext(), TimeUtils
//                                .dateFromNotYMDHM(HexUtil
//                                        .encodeHexStr(mKeyDefineData.getmKeyBasicInfo()
//                                                .getKeyIssueTime())));
//                        startTime = TimeFormatUtil.showDateTime(getContext(), TimeUtils
//                                .dateFromNotYMDHM(HexUtil
//                                        .encodeHexStr(mKeyDefineData
//                                                .getUserKeyInfo()
//                                                .getKeyStartTime())));
//                        endTime = TimeFormatUtil.showDateTime(getContext(), TimeUtils
//                                .dateFromNotYMDHM(HexUtil
//                                        .encodeHexStr(mKeyDefineData
//                                                .getUserKeyInfo()
//                                                .getKeyEndTime())));
//
////                        getContext().runOnUiThread(new Runnable() {
////                            @Override
////                            public void run() {
////                                mTvActivityCollectkeyIssuetime.setText(getString(R.string.issue_time) + TimeUtils.localDateTimeFormat(TimeUtils
////                                        .dateFromNotYMDHM(HexUtil
////                                                .encodeHexStr(mKeyDefineData
////                                                        .getUserKeyInfo()
////                                                        .getKeyIssueTime()))));
////                                mTvActivityCollectkeyStarttime.setText(getString(R.string.start_time) + ": " + TimeUtils.localDateTimeFormat(TimeUtils
////                                        .dateFromNotYMDHM(HexUtil
////                                                .encodeHexStr(mKeyDefineData
////                                                        .getUserKeyInfo()
////                                                        .getKeyStartTime()))));
////                                mTvActivityCollectkeyEndtime.setText(getString(R.string.end_time) + ": " + TimeUtils.localDateTimeFormat(TimeUtils
////                                        .dateFromNotYMDHM(HexUtil
////                                                .encodeHexStr(mKeyDefineData
////                                                        .getUserKeyInfo()
////                                                        .getKeyEndTime()))));
////                            }
////                        });
//
////                        setText("Valid Day Count: "
////                                + String.valueOf(mKeyDefineData
////                                .getUserKeyInfo().getValidDayCount()));
//
//                    }
//
//                    @Override
//                    public void readUserKeyFailed() {
//                        // TODO Auto-generated method stub
//                        Log.e(getContext().getClass().getSimpleName() + "userkey", "\nRead user key failed \n");
//
//                        mResult = false;
//                    }
//
//                });
//    }

    private void readKeyEvent(final ReaderPortThread mReaderPortThread,
                              final KeyBasicInfo pKeyBasicInfo, final KeyEventInfo pKeyEventInfo) {

        mReaderPortThread.getmPortReadBiz().readEvent(pKeyBasicInfo,
                pKeyEventInfo, new OnPortListener.OnReadEventListener() {

                    @Override
                    public void readEventSuccess() {
                        // TODO Auto-generated method stub
                        Log.e("readevent", "\nRead key events successfully \n");
                        mResult = true;
                        mList.clear();
                        EventDao eventDao = new EventImpl();
                        LockDao lockDao = new LockImp();
                        for (KeyEventInfo.EventInfo event : pKeyEventInfo.getEventList()) {
                            EventData eventData = new EventData();
                            eventData.setKeytype(pKeyBasicInfo.getType());
                            eventData.setKeyfactorynumber(HexUtil.encodeHexStr(pKeyBasicInfo.getSerial()));
                            eventData.setType(1);
                            eventData.setTime(event.time);
                            eventData.setLockid(String.valueOf(event.lockId));
                            eventData.setEvent(event.event);
                            eventData.setVersion(mKeyBasicInfo.getVersion());
                            eventData.setUserid(String.valueOf(event.keyId));
                            eventData.setPostion(Version.INDOOR);
                            eventDao.addEvent(eventData);
                            LogData logData = new LogData();
                            logData.setTime(event.time);
                            logData.setLockid(event.lockId);
                            logData.setUserid(event.keyId);
                            logData.setType(event.event);
                            LockData lockData = lockDao.findBylockId(String.valueOf(event.lockId));
                            if (lockData == null) {
                                logData.setLockname("");
                            } else {
                                logData.setLockname(lockData.getName());
                            }
                            KeyUserData keyUserData = mKeyUserDao.findByUserid(String.valueOf(event.keyId));
                            if (!keyUserData.equals("0")) {
                                logData.setUserlastname(keyUserData.getLname());
                                logData.setUserfirstname(keyUserData.getFname());

                            } else {
                                logData.setUserlastname("");
                                logData.setUserfirstname("");
                            }
                            mList.add(logData);
                        }
                        finishCount = 1;
                    }

                    @Override
                    public void readEventFailed() {
                        // TODO Auto-generated method stub
                        Log.e(getContext().getClass().getSimpleName() + "readevent", "\nRead key events failed \n");
                        mResult = false;
                    }

                });
    }

    private void resetKey(final ReaderPortThread mReaderPortThread, final KeyBasicInfo pKeyBasicInfo) {
        mReaderPortThread.getmPortReadBiz().resetKey(pKeyBasicInfo,
                new OnPortListener.OnResetKeyListener() {

                    @Override
                    public void resetKeySuccess() {
                        // TODO Auto-generated method stub
                        Log.e("reset", "Reset key successfully \n");
                        mResult=true;
                        finishCount = 2;
//                       doListen();
                    }

                    @Override
                    public void resetKeyFailed() {
                        // TODO Auto-generated method stub
                        Log.e(getContext().getClass().getSimpleName() + "reset", "Reset key failed \n");
                        mResult = false;
                    }
                });
    }

    private void open(){

        BroadcastUtils.send(getActivity(), STOP);

        Action = OPENDOOR;
        byte[] key = {1, 0, 0, 0};
        mKeyHolderService.sendData(new KeyHolderData((byte) 1, (byte) 2, (byte) 0x02, key));
//        mSubscription = Observable.create(new Observable.OnSubscribe<String>() {
//            @Override
//            public void call(Subscriber<? super String> subscriber) {
//                getActivity().runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        mIHardware.DoorState(0);
//                    }
//                });
//                mCurrentUserDao.deleteByKeysn(SN);
//                subscriber.onNext(getString(R.string.ic_three));
//                SystemClock.sleep(1000);
//                subscriber.onNext(getString(R.string.ic_two));
//                SystemClock.sleep(1000);
//                subscriber.onNext(getString(R.string.ic_one));
//                SystemClock.sleep(1000);
//                subscriber.onCompleted();
//
//            }
//        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
//            @Override
//            public void onCompleted() {
//                ToastUtils.showShortToast(getContext(), getString(R.string.return_key_and_close_door));
//                mPvActivityCollectkeyTime.setVisibility(View.GONE);
//                MainActivity.open = true;
//                byte[] key = {};
//                mKeyHolderService.sendData(new KeyHolderData(address, KeyHolderCmd.READ_KEY_LOCKED_COUNT, key));
//            }
//
//            @Override
//            public void onError(Throwable e) {
//                Log.e(getContext().getClass().getSimpleName() + "collecterror", e.toString());
//            }
//
//            @Override
//            public void onNext(String s) {
//                byte[] key = TimeFormatUtil.inttoTwoBytes(50);
//                mKeyHolderService.sendData(new KeyHolderData(address, (byte) 0x0c, key));
//                mPvActivityCollectkeyTime.setIconText(s);
//                mPvActivityCollectkeyTime.setVisibility(View.VISIBLE);
//                startAni();
//            }
//        });
    }
    private void startAni() {
        if (objectAnimator == null) {
            objectAnimator = ObjectAnimator.ofFloat(mPvActivityCollectkeyTime, "alpha", 1f, 0f);
            objectAnimator.setDuration(1000);
        }
        objectAnimator.start();
    }

    private void clearAni() {
        if (objectAnimator != null && objectAnimator.isRunning()) {
            objectAnimator.cancel();
        }
    }

    @OnClick(R.id.tv_activity_collectkey_write)
    public void onClick() {
        errorCount = 0;
        mTvActivityCollectkeyWrite.setVisibility(View.GONE);
        mSvActivityCollectkeyLoading.setVisibility(View.VISIBLE);
        doListen();
    }

    private IHardware mIHardware;

    public void setmIHardware(IHardware hardware) {
        mIHardware = hardware;
    }
}
